package jpavlich.cardsorter;

import java.awt.Color;
import java.util.ArrayList;
import java.util.List;

import org.icepdf.core.pobjects.Document;

import fr.inria.zvtm.animation.Animation;
import fr.inria.zvtm.animation.interpolation.IdentityInterpolator;
import fr.inria.zvtm.engine.Camera;
import fr.inria.zvtm.engine.View;
import fr.inria.zvtm.engine.ViewPanel;
import fr.inria.zvtm.engine.VirtualSpace;
import fr.inria.zvtm.engine.VirtualSpaceManager;
import fr.inria.zvtm.event.ViewListener;
import fr.inria.zvtm.glyphs.Glyph;
import fr.inria.zvtm.glyphs.IcePDFPageImg;

public class CardSorter {

	private VirtualSpaceManager vsm = VirtualSpaceManager.INSTANCE;
	private VirtualSpace vs;
	private ViewListener eventListener;
	private Camera camera;
	private View view;

	CardSorter(String viewType) {
		// VirtualSpaceManager.setDebug(true);
		eventListener = new CardSorterEventListener(this);
		vs = vsm.addVirtualSpace("vs");
		camera = vs.addCamera();
		List<Camera> cameras = new ArrayList<Camera>();
		cameras.add(camera);
		vs.getCamera(0).setZoomFloor(-100f);
		view = vsm.addFrameView(cameras, "Card Sorter", viewType, 1024, 768,
				false, true, true, null);
		view.setBackgroundColor(Color.LIGHT_GRAY);
		view.setListener(eventListener);
		vs.getCamera(0).setAltitude(1000);
		view.getGlobalView(camera, 500, 4f);
		view.setNotifyCursorMoved(true);
		createGlyps();
	}

	void createGlyps() {
		addPDF("data/test.pdf", 2);
	}

	private void addPDF(String pdfFile, float detailFactor) {
		try {
			Document d = new Document();
			d.setFile(pdfFile);
			int page_width = (int) d.getPageDimension(0, 0).getWidth();
			for (int i = 0; i < d.getNumberOfPages(); i++) {
				IcePDFPageImg page = new IcePDFPageImg((long) (i * page_width
						* 1.1f * detailFactor), 0, 0, d, i, detailFactor, 1.0f);
				vs.addGlyph(page);
			}
			d.dispose();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		new CardSorter(View.STD_VIEW);
	}

	public Camera getCamera() {
		return camera;
	}

	public VirtualSpace getVs() {
		return vs;
	}

	public void animate() {
		Glyph g = stickGlyph();
		System.out.println("Animating " + g);
		if (g != null) {
			Animation anim = vsm
					.getAnimationManager()
					.getAnimationFactory()
					.createCameraTranslation(500, camera, g.getLocation(), false, IdentityInterpolator.getInstance(), null);
			vsm.getAnimationManager().startAnimation(anim, true);
			unstickGlyphs();
		}

	}

	public Glyph stickGlyph() {
		Glyph g = view.getPanel().lastGlyphEntered();
		if (g != null) {
			view.getPanel().getVCursor().stickGlyph(g);
			getVs().onTop(g);
		}
		return g;
	}

	public void unstickGlyphs() {
		view.getPanel().getVCursor().unstickLastGlyph();

	}

}
